import Base from './base'
import Vue from 'vue'
import vm from '@/main'
import NewMessageNotify from '@/components/DuoJuHe/Chat/notify/NewMessageNotify'
import { clearUnreadNumChatUsersChatList, saveChatUsersChatList } from '@/api/chat/im/chatList'
import { formateTalkItem, findTalkIndex, toTalk } from '@/utils/talk'
import { parseTime } from '@/utils/functions'
import router from '@/router'
import SocketInstance from '@/utils/socket-instance'
/**
 * 好友状态事件
 */
class Talk extends Base {
  /**
   * @var resource 资源
   */
  resource

  /**
   * 发送者ID
   */
  senderId = 0

  /**
   * 接收者ID
   */
  receiverId = 0

  /**
   * 聊天类型[1:私聊;2:群聊;]
   */
  talkType = 0

  /**
   * 初始化构造方法
   *
   * @param {Object} resource Socket消息
   */
  constructor(resource) {
    super()

    this.senderId = resource.data.senderId
    this.receiverId = resource.data.receiverId
    this.talkType = resource.data.talkType

    this.resource = resource.data.messageBody
  }

  /**
   * 判断消息发送者是否来自于我
   * @returns
   */
  isCurrSender() {
    return this.senderId == this.getAccountId()
  }

  /**
   * 获取对话索引
   *
   * @return String
   */
  getIndexName() {
    if (this.talkType == 2) {
      return `${this.talkType}_${this.receiverId}`
    }

    let receiverId = this.isCurrSender() ? this.receiverId : this.senderId

    return `${this.talkType}_${receiverId}`
  }

  /**
   * 消息浮动方式
   *
   * @returns
   */
  getFloatType() {
    let userId = this.resource.userId
    if (userId == 0) return 'center'
    return userId == this.getAccountId() ? 'right' : 'left'
  }

  /**
   * 获取聊天列表左侧的对话信息
   */
  getTalkText() {
    let text;
    switch (this.resource.msgType) {
      case 1:
        text = this.resource.content
        break
      case 2:
        let fileType = this.resource.file.fileType
        text = fileType == 1 ? '[图片消息]' : '[文件消息]'
        break
      case 3:
        text = '[会话记录]'
        break
      case 4:
        text = '[代码消息]'
        break
      case 5:
        text = '[投票消息]'
        break
      case 6:
        text = '[群组公告]'
        break
      case 7:
        text = '[好友申请]'
        break
      case 8:
        text = '[登录提醒]'
        break
      case 9:
        text = '[入群退群消息]'
        break
      default:
        text = '[系统消息]'
    }

    return text
  }

  handle() {
    let store = this.getStoreInstance()

    // 判断当前是否在聊天页面
    if (!this.isTalkPage()) {
      store.commit('INCR_UNREAD_NUM')

      // 判断消息是否来自于我自己，否则会提示消息通知
      return !this.isCurrSender() && this.showMessageNotice()
    }

    // 判断会话列表是否存在，不存在则创建
    if (findTalkIndex(this.getIndexName()) == -1) {
      return this.addTalkItem()
    }

    let isTrue = this.isTalk(this.talkType, this.receiverId, this.senderId)

    // 判断当前是否正在和好友对话
    if (isTrue) {
      this.insertTalkRecord()
    } else {
      this.updateTalkItem()
    }
  }

  /**
   * 显示消息提示
   * @returns
   */
  showMessageNotice() {
    if('/imChatAdmin/myImChatList'!==router.currentRoute.path){
      return
    }
    let avatar
    let realName = this.resource.realName
    let talkType = this.resource.talkType
    let receiverId = this.receiverId
    if (talkType == 2) {
      avatar = this.resource.groupAvatar
      realName += `【 ${this.resource.groupName} 】`
    } else {
      avatar = this.resource.headPortrait
      realName += `【 ${this.resource.realName} 】`
      receiverId = this.senderId
    }
    this.$notify({
      message: vm.$createElement(NewMessageNotify, {
        props: {
          avatar,
          talkType,
          realName,
          content: this.getTalkText(),
          datetime: this.resource.createTime,
        },
      }),
      customClass: 'im-notify',
      duration: 3000,
      position: 'top-right',
      onClick: function() {
        this.close()
        toTalk(talkType, receiverId)
      },
    })
  }

  /**
   * 加载对接节点
   */
  addTalkItem() {
    let receiverId = this.senderId
    let talkType = this.talkType
    if (talkType == 1 && this.receiverId != this.getAccountId()) {
      receiverId = this.receiverId
    } else if (talkType == 2) {
      receiverId = this.receiverId
    }
    saveChatUsersChatList({
      talkType:talkType,
      receiverId:receiverId,
    }).then(response => {
      this.getStoreInstance().commit('PUSH_TALK_ITEM', formateTalkItem(response.data))
    })
  }


  /**
   * 插入对话记录
   */
  insertTalkRecord() {
    let store = this.getStoreInstance()
    let record = this.resource

    record.float = this.getFloatType()

    store.commit('PUSH_DIALOGUE', record)

    // 获取聊天面板元素节点
    let el = document.getElementById('duoJuHeChatPanel')

    // 判断的滚动条是否在底部
    let isBottom = Math.ceil(el.scrollTop) + el.clientHeight >= el.scrollHeight

    if (isBottom || record.userId == this.getAccountId()) {
      Vue.nextTick(() => {
        el.scrollTop = el.scrollHeight
      })
    } else {
      store.commit('SET_TALK_UNREAD_MESSAGE', {
        content: this.getTalkText(),
        realName: record.realName,
      })
    }

    store.commit('UPDATE_TALK_ITEM', {
      indexName: this.getIndexName(),
      msgText: this.getTalkText(),
      updateTime: parseTime(new Date()),
    })
    if (this.talkType === 1 && this.getAccountId() !== this.senderId) {
      clearUnreadNumChatUsersChatList({
        talkType: this.talkType,
        receiverId: this.senderId,
      })
    }else if (this.talkType === 2 && this.getAccountId() !== this.senderId) {
      clearUnreadNumChatUsersChatList({
        talkType: this.talkType,
        receiverId: this.receiverId,
      })
    }
  }

  /**
   * 更新对话列表记录
   */
  updateTalkItem() {
    let store = this.getStoreInstance()

    store.commit('INCR_UNREAD_NUM')

    store.commit('UPDATE_TALK_MESSAGE', {
      indexName: this.getIndexName(),
      msgText: this.getTalkText(),
      updateTime: parseTime(new Date()),
    })
    //发送websocket消息
    /*SocketInstance.emit('send', "echo")*/
  }
}

export default Talk
